//
//  SelectHosNameViewController.m
//  YuanCheng
//
//  Created by dongshangtong on 16/4/11.
//  Copyright © 2016年 dongshangtong. All rights reserved.
//

#import "SelectHosNameViewController.h"
#import "HosNameListModel.h"
@interface SelectHosNameViewController () <UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate>


@property (nonatomic ,weak )UITableView *tableView;
@property (nonatomic ,weak )UITextField *textField;
@property (nonatomic,assign) NSInteger indexPage;

@property (nonatomic ,strong )NSMutableArray *dataSuore;


@end

@implementation SelectHosNameViewController


-(NSMutableArray *)dataSuore
{
    
    if (!_dataSuore) {
        self.dataSuore = [NSMutableArray array];
    }
    
    
    return _dataSuore;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _indexPage = 1;
    [self setupUI];
    [self getData];
    
    //[self getHosNameDate];
    
}

- (void)setupUI {
    
    [self presentLoadingTips:nil];
    self.navigationItem.title = @"请选择医院名称";
    
    //    1.设置搜索框
    self.view.backgroundColor = BackgroundColor;
    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(MarginWidth, 20 , MaxViewWidth, 41)];
    textField.backgroundColor = [UIColor whiteColor];
    
    
    
    //    1.2. 设置搜索按钮
    UIButton *rightView = [UIButton buttonWithType:UIButtonTypeCustom];
    rightView.frame = CGRectMake(0, 0, 52, 41);
    rightView.backgroundColor = GreenColor;
    [rightView setImage:[UIImage imageNamed:@"hos_search"] forState:UIControlStateNormal];
    
    [rightView addTarget:self action:@selector(searchAction) forControlEvents:UIControlEventTouchUpInside];
    textField.rightView = rightView;
    textField.rightViewMode = UITextFieldViewModeAlways;
    
    textField.textColor = LigthGray;
    textField.font = SubTitleFont;
    textField.tintColor = GreenColor;
    [textField setReturnKeyType:UIReturnKeyDone];
    [textField becomeFirstResponder];
    textField.delegate = self;
    [self.view addSubview:textField];
    _textField = textField;
    
    if (self.flag) {
        
        UIImage *img= [UIImage imageNamed:@"back"];
        img= [img imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        UIButton *navBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 5, 40, 30)];
        navBtn.imageEdgeInsets= UIEdgeInsetsMake(0, -30, 0, 0);
        [navBtn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
        [navBtn setImage:img forState:UIControlStateNormal];
        
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:navBtn];
    }
    
    
    UITableView *tableView = [[UITableView alloc] init];
    CGFloat tableHeight = SCREEN_HEIGHT - 73 - NAVGATION_ADD_STATUSBAR_HEIGHT;
    tableView.frame = CGRectMake(0, 73 , SCREEN_WIDTH, tableHeight);
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:tableView];
    _tableView = tableView;
    _tableView.tableFooterView= [UIView new];
    
}

- (void)backClick
{
    if (self.flag) {
        
        if ([_flag isEqualToString:@"updateProfile"]) {
            
            [self.navigationController popViewControllerAnimated:YES];
            
        }else {
            
            [self dismissViewControllerAnimated:YES completion:^{
            }];
        }
        
        
    }else{
        [self.navigationController popViewControllerAnimated:YES];
        
        
    }
}

#pragma mark - textField 代理方法
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [textField resignFirstResponder];
    return  YES;
}

- (void)getData  {
    
    
    NSArray *hosname = [YCCommonTool queryHosnames];
    
    if (hosname.count>0) {
        [self.dataSuore addObjectsFromArray:[HosNameListModel mj_objectArrayWithKeyValuesArray:hosname]];
        
        
        
    }else{
        
        [self presentLoadingTips:nil];
        NSString *url = kHospitalListUrl;
//        NSString *url =[YCUrlManager sharedInstance].hospitalListUrl;
        
        NSDictionary *params = @{
                                 @"yw_id":yw_id,
                                 @"hos_name":@""
                                 };
        [DownloadData post:url params:params success:^(id json) {
            
            [self.dataSuore addObjectsFromArray:[HosNameListModel mj_objectArrayWithKeyValuesArray:json]];
            
            [YCCommonTool saveHosname:json];
            
            [self dismissTips];
            [self.tableView reloadData];
            
        } failure:^(NSError *error) {
            [self dismissTips];
        } ];
    }
}

- (void)searchAction {
    [self.textField resignFirstResponder];
    NSString *hosName = @"";
    if (self.textField.text) {
        hosName = self.textField.text;
    }
     NSString *url = kHospitalListUrl;
//    NSString *url =[YCUrlManager sharedInstance].hospitalListUrl;
    
    NSDictionary *params = @{
                             @"yw_id":yw_id,
                             @"hos_name":hosName
                             };
    
    [DownloadData post:url params:params success:^(id json) {
        
        [self dismissTips];
        [self.dataSuore removeAllObjects];
        [self.dataSuore addObjectsFromArray:[HosNameListModel mj_objectArrayWithKeyValuesArray:json]];
        [_tableView reloadData];
        
    } failure:^(NSError *error) {
        [self dismissTips];
    }];
    
    //    上拉加载，下拉刷新
    __weak typeof(self) weakself = self ;
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // [self setupData];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakself.tableView.mj_header endRefreshing];
        });
    }];
    
    self.tableView.mj_footer = [MJRefreshAutoGifFooter footerWithRefreshingBlock:^{
        
        [weakself dropdownMoreDate];
    }];
}





-(void)getHosNameDate {
    
    NSArray *hosname = [YCCommonTool queryHosnames];
    
    if (hosname.count>0) {
        [self.dataSuore addObjectsFromArray:[HosNameListModel mj_objectArrayWithKeyValuesArray:hosname]];
        
    }else{
        [self presentLoadingTips:nil];
        NSString *hosName = @"";
        NSString *url = kHoslistUrl;
//        NSString *url =[YCUrlManager sharedInstance].hoslistUrl;
        NSDictionary *params =@{
                                @"page_num":@(self.indexPage),
                                @"lat":@"",
                                @"lng":@"",
                                @"province_id":@"",
                                @"level_id":@"",
                                @"serve_id":@"",
                                @"hos_name":hosName
                                };
        
        [DownloadData post:url params:params success:^(id json) {
            
            
            [self dismissTips];
            [YCCommonTool saveHosname:json];
            
            [self.dataSuore addObjectsFromArray:[HosNameListModel mj_objectArrayWithKeyValuesArray:json]];
            
        } failure:^(NSError *error) {
            
            [self dismissTips];
            
            
        }];
        
        
    }
    
}



//上拉刷新
-(void)dropdownMoreDate {
    
    _indexPage++;
    NSString *hosName = @"";
    if (self.textField.text) {
        hosName = self.textField.text;
    }
    NSString *url = kHoslistUrl;
//    NSString *url =[YCUrlManager sharedInstance].hoslistUrl;
    NSDictionary *params =@{
                            @"page_num":@(self.indexPage),
                            @"lat":@"",
                            @"lng":@"",
                            @"province_id":@"",
                            @"level_id":@"",
                            @"serve_id":@"",
                            @"hos_name":hosName
                            };
    
    [DownloadData post:url params:params success:^(id json) {
        //缓存
        //[YCtool saveHospitals:json];
        [self.dataSuore addObjectsFromArray:[HosNameListModel mj_objectArrayWithKeyValuesArray:json]];
        //        [self.dataSource addObjectsFromArray:[HospitalModel mj_objectArrayWithKeyValuesArray:json]];
        
        if ([HosNameListModel mj_objectArrayWithKeyValuesArray:json].count > 0) {
            [self.tableView reloadData];
            
            [self.tableView.mj_footer endRefreshing];
        }else {
            
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        
    } failure:^(NSError *error) {
        
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }];
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    
    
    return  self.dataSuore.count;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"cellID";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    
    HosNameListModel *hos = self.dataSuore[indexPath.row];
    
    cell.textLabel.text= hos.hosName;
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    HosNameListModel *hos = self.dataSuore[indexPath.row];
    
    
    if (self.flag) {
        
        if ([_flag isEqualToString:@"updateProfile"]) {
            //        修改基本资料
            NSInteger columnValue = hos.hosId;
            NSString *columnName = @"hos_id";
            NSString *userId = [[NSUserDefaults standardUserDefaults] objectForKey:KEXPERTID]
            ;
            NSString *url = kEditOkUrl;
//            NSString *url = [YCUrlManager sharedInstance].editOkUrl;
            
            NSDictionary *params = @{
                                     @"expert_id":userId,
                                     @"column_name":columnName,
                                     @"column_value":@(columnValue)
                                     };
            
            [DownloadData post:url params:params success:^(id json) {
                
                if ([json[@"error_code"] isEqualToString:@"ok"]) {
                    
                    [self presentSuccessTips:@"修改成功!!"];
                    
                    
                    if (self.hosListName) {
                        self.hosListName(hos);
                    }
                    
                    [self.navigationController popViewControllerAnimated:YES];
                }else {
                    
                    NSString *errorStr = [YCCommonTool getErrorStr:json[@"error_code"]];
                    [self presentFailureTips:[NSString stringWithFormat:@"修改失败！- %@", errorStr]];
                }
            } failure:^(NSError *error) {
                NSLog(@"%@", error.localizedDescription);
                [self presentFailureTips:@"修改失败！"];
            }];
            
        }else {
            
            if (self.hosListName) {
                self.hosListName(hos);
            }
            
            [self dismissViewControllerAnimated:YES completion:^{
                
            }];
        }
        
    }else{
        
        if (self.hosListName) {
            self.hosListName(hos);
        }
        
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}

@end
